package com.applet.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Objects;

/**
 * @author “XuShao”
 * @date 2024/12/16 21:54
 * @description
 */
@Component
@Slf4j
public class FileUtil {
    /**
     * 校验文件大小和文件后缀
     * @param file
     * @param size
     * @param suffix
     * @return
     */
    public boolean validate(MultipartFile file, Double size, List<String> suffix) {
        log.info("=== 校验图片中 ===");
        if(file == null) return false;
        log.info("校验图片 => {}", file);
        if(file.getSize() > (size * 1024 * 1024)) return false;
        log.info("校验图片 => {}", file.getSize());
        suffix = suffix.stream().map(String::toUpperCase).toList();
        log.info("校验图片 => {}", suffix);
        if(!suffix.contains(getFileSuffix(Objects.requireNonNull(file.getOriginalFilename())).substring(1).toUpperCase())) return false;
        return true;
    }

    // 获取文件后缀
    public String getFileSuffix(String fileName) {
        int lastIndex = fileName.lastIndexOf(".");
        if (lastIndex == -1) return fileName;
        return fileName.substring(lastIndex);
    }

}
